#include "apue.h"
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>

int initserver(int type, const struct sockaddr *addr, socklen_t alen, int qlen) {
    int fd, err;
    int reuse= 1;

    if ((fd= socket(addr->sa_family, type, 0)) < 0)
        return(-1);
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0)
        goto errout; 
    if (bind(fd, addr, alen) < 0)
        goto errout;
    if (type == SOCK_STREAM || type == SOCK_SEQPACKET)
        if (listen(fd, qlen) < 0)
            goto errout;
    return fd;

errout:
    err= errno;
    close(fd);
    errno= err;
    return(-1);
}

int main() {
    struct addrinfo *ailist, *aip;
    struct addrinfo hint;
    int fd, clfd, err, n;
    char *host;

    if ((n= sysconf(_SC_HOST_NAME_MAX)) < 0)
        n= 256;   /* best guess */
    if ((host= malloc(n)) == NULL)
        err_sys("malloc error");
    if ((err= gethostname(host, n)) < 0)
        err_sys("gethostname error");

    memset(&hint, 0, sizeof(hint));
    hint.ai_flags= AI_CANONNAME;
    hint.ai_socktype= SOCK_STREAM;
    hint.ai_addr= NULL;
    hint.ai_next= NULL;

    if ((err= getaddrinfo(host, "ruptime", &hint, &ailist)) != 0)
        err_quit("ruptimed: getaddrinfo error: %s", gai_strerror(err));

    printf("host: %s\n", host);
    for (aip= ailist; aip!=NULL; aip= ailist->ai_next) {
        if ((fd= initserver(SOCK_STREAM, aip->ai_addr, aip->ai_addrlen, 0)) < 0) {
            err= errno;
            continue;
        }

        if ((clfd= accept(fd, NULL, NULL)) < 0)
            err_sys("accept error");
        else {
            printf("success quit\n");
            exit(0);
        }
                
    }
    err_exit(err, "initserver error: %s\n");
}
